package com.borzaindustries.mkdummy;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.*;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.*;

import android.widget.*;

public class DirectoryBrowser extends ListActivity {
	private ArrayList<String> items;
	private String currentPath;
	final String STARTDIR = "/sdcard";
	final String ROOT = "/";
	public final static String SELECTED_PATH = "selected_path";
	public static final int BROWSE_DIR = 0;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.directory_browser);
		registerForContextMenu(getListView());
		this.setTitle(R.string.directory_browser_title);
		currentPath = STARTDIR;
		getFiles();
	}

	// CONTEXT MENU
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		getMenuInflater().inflate(R.menu.directory_browser_context_menu, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// getMenuInfo
		switch (item.getItemId()) {
		case R.id.menu_ok:
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
					.getMenuInfo();
			String selectedPath = items.get((int) info.id);
			exitWithDir(currentPath + "/" + selectedPath);
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	private void showAddDialog() {
		final Dialog dialog = new Dialog(this);
		dialog.getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
				WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

		dialog.setTitle(R.string.create_directory);
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View dialogView = inflater.inflate(
				R.layout.directory_browser_create_directory_dialog, null);
		dialog.setContentView(dialogView);
		ImageButton okButton = (ImageButton) dialogView.findViewById(R.id.ok);
		ImageButton cancelButton = (ImageButton) dialogView
				.findViewById(R.id.cancel);
		okButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// get text of text box
				EditText et = (EditText) dialogView
						.findViewById(R.id.edit_text);
				String dirName = et.getText().toString();
				if(dirName.length() == 0)
				{
					Toast.makeText(getBaseContext(), R.string.directory_browser_empty_filename, Toast.LENGTH_SHORT).show();
					return;
				}
				File fullDir = new File(currentPath,dirName);
				String fullPath = fullDir.getAbsolutePath();
				try{
					fullPath = fullDir.getCanonicalPath();
				}
				catch(Exception e){
					
				}
				if (!createDirectory(dirName)) {
					Toast.makeText(
							getBaseContext(),
							getBaseContext().getText(
									R.string.cannot_create_directory)
									+ " " + fullPath, Toast.LENGTH_SHORT)
							.show();
					return;
				}
				dialog.dismiss();
				Toast.makeText(
						getBaseContext(),
						getBaseContext().getText(R.string.directory_browser_created)
						+ " " +fullPath,
						Toast.LENGTH_SHORT).show();
				browsePath(fullPath);
			}
		});
		cancelButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	// OPTIONS MENU
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.directory_browser_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.ok:
			exitWithDir(currentPath);
			return true;
		case R.id.cancel:
			setResult(RESULT_CANCELED);
			finish();
			return true;
		case R.id.add:
			showAddDialog();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	// LIST VIEW CLICK
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		int selectedRowIndex = (int) id;
		String selectedPath = items.get(selectedRowIndex);
		// check if we selected "/" item
		if (selectedPath == ROOT) {
			goToRoot();
			return;
		}
		// move to selected directory
		File file = new File(currentPath + "/" + items.get(selectedRowIndex));
		String newPath;
		try {
			newPath = file.getCanonicalPath();
		} catch (Exception e) {
			newPath = file.getAbsolutePath();
		}
		browsePath(newPath);
		return;
	}

	// DIRECTORY NAVIGATION
	private void goToRoot() {
		browsePath(ROOT);
	}
	
	private void browsePath(String path){
		currentPath = path;
		getFiles();
	}

	private void getFiles() {
		File currentPathFile = new File(currentPath);
		File[] files = currentPathFile.listFiles();
		TextView t = (TextView) findViewById(R.id.title);
		t.setText("[" + currentPath + "]");
		items = new ArrayList<String>();

		int specialItemsCount = 0;
		if (currentPath != ROOT) {
			items.add(ROOT); // root directory
			specialItemsCount++;
		}
		if (currentPathFile.getParent() != null) {
			items.add(".."); // parent directory
			specialItemsCount++;
		}

		for (File f : files) {
			if (f.isDirectory())
				items.add(f.getName());
		}
		Collections.sort(items);
		// sort / and ..; if they are present; sort() sorted them the wrong way
		if (specialItemsCount == 2) {
			String temp = items.get(0);
			items.set(0, items.get(1));
			items.set(1, temp);
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.directory_browser_row, items);
		setListAdapter(adapter);
	}

	// create directory
	private boolean createDirectory(String name) {
		File dir = new File(currentPath, name);
		try {
			return dir.mkdirs();
		} catch (Exception e) {
			return false;
		}
	}

	// EXIT
	private void exitWithDir(String path) {
		Intent data = new Intent();
		data.putExtra(SELECTED_PATH, path);
		setResult(RESULT_OK, data);
		finish();
	}
}